#coding:utf-8
'''
create on 2017-04-20
@author:sandy
'''

from pycommon import TBaseFactory
import Client
import time
import logging

class ClientFactory(TBaseFactory.TBaseFactory):

    def __init__(self):
        self.__uidmap = {}
        TBaseFactory.TBaseFactory.__init__(self)

    def createClient(self, pid, addr):
        return Client.ClientSrv(pid, addr)

    def checkClients(self, clients):
        curtime = time.time()
        for c in clients:
            #c.sendKeepAlive()
            if c.getState() == Client.CLIENT_STATE_TO_CLOSE and curtime-c.toclosetime > 10:
                c.abort()
            elif curtime - c.getLastActiveTime() > 600:
                c.abort()


    def removeProtocol(self, prot):
        uid = prot.getUid()
        if uid != 0:
            mapproto = self.__uidmap.get(uid)
            if mapproto != None and mapproto == prot:
                self.__uidmap.pop(uid,None)
            else:
                logging.warn(u'removeProtocol uid = %d error,maybe has two clients to use the same uid',uid)
        else:
            logging.warn("removeProtocol uid=0")
        TBaseFactory.TBaseFactory.removeProtocol(self, prot)

    def mapClient(self, uid, client):
        self.__uidmap[uid] = client

    def getClientSrvByUid(self, uid):
        return self.__uidmap.get(uid)

    def getClientSrvByPid(self, pid):
        return self.getProtocol(pid)

instance = ClientFactory()

if __name__ == "__main__":
    pass